<template>
  <div class="app-container device-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="设备名称" v-model="listQuery.title">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="float:right" @click="handleCreate" type="primary" icon="edit">添加</el-button>
      <el-button class="filter-item" style="float:right" type="primary" icon="document" @click="handleDownload">导出</el-button>
    </div>

    <el-table :key='tableKey' :data="list" 
    @sort-change = "sortChange"
    border fit highlight-current-row style="width: 100%">

      <el-table-column align="center" fixed sortable="custom" prop="id" label="序号" width="100">
        <template scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="设备id" width="120">
        <template scope="scope">
          <span>{{scope.row.DeviceId}}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" label="设备名称">
        <template scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.DeviceName}}</span>
        </template>
      </el-table-column>

      <el-table-column width="300px" align="center" label="Secret">
        <template scope="scope">
          <span>{{scope.row.DeviceSecret}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150px"  align="center" label="产品key">
        <template scope="scope">
          <span>{{scope.row.ProductKey}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150px" sortable prop="created_at" align="center" label="时间">
        <template scope="scope">
          <span>{{scope.row.created_at }}</span>
        </template>
      </el-table-column>

      <el-table-column width="200px" align="center" fixed="right" label="操作" >
        <template scope="scope">
          <el-button  size="small" type="success" @click="handleView(scope.row)">查看
          </el-button>
          <el-button size="small" type="success" @click="handleMessage(scope.row)">通信
          </el-button>
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.page_limit" layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total">
      </el-pagination>
    </div>

    <el-dialog style="max-height:90%" :title="DeviceDailog.textMap[DeviceDailog.dialogStatus]" :visible.sync="DeviceDailog.visible">
      <el-form class="small-space" :model="deviceForm" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="设备名称">
          <el-input v-model="deviceForm.DeviceName" placeholder="输入设备名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="DeviceDailog.visible = false">取 消</el-button>
        <el-button v-if="DeviceDailog.dialogStatus=='create'" type="primary" @click="create">确 定</el-button>
        <el-button v-else type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除提示 -->
    <el-dialog
      title="提示"
      :visible.sync="delDeviceDialogVisible"
      width="30%">
      <span>确定要删除该产品吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delDeviceDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delDevice">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设备信息 -->
    <el-dialog
      title="设备信息"
      :visible.sync="deviceInfoDialogVisible">
      <el-collapse v-model="activeNames">
        <el-collapse-item title="设备信息" name="1">
          <div>设备名称：{{deviceInfo.DeviceName}}</div>
          <div>设备Id：{{deviceInfo.DeviceId}}</div>
          <div>设备Secret：{{deviceInfo.DeviceSecret}}</div>
          <div>产品key：{{deviceInfo.ProductKey}}</div>
        </el-collapse-item>
        <el-collapse-item title="设备状态" name="2">
          <div>设备状态：{{statusInfo.Status}}</div>
        </el-collapse-item>
        <el-collapse-item title="设备影子" name="3">
          <div>设备影子：</div>
          <div class="editor-container">
            <json-editor ref="jsonEditor" v-model="shadowInfo"></json-editor>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-dialog>
    <!-- 通信 -->
    <el-dialog
      title="设备通信"
      width="70%"
      :visible.sync="deviceMessageDialogVisible">
      <div class="device_message">
        <el-row>
          <el-col :span="12" style="border-right:1px solid #ddd;padding-right:10px">
            <p>向topic 发送消息</p>
            <el-form label-width="40px" >
              <el-form-item label="topic">
                <el-select v-model="sendToTopicForm.cur_topic" style="width:100%" placeholder="请选择topic">
                  <el-option
                    v-for="item in sendToTopicForm.topicList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="内容">
                <el-input v-model="sendToTopicForm.message" placeholder="发送内容"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button  size="medium" type="success" @click="sendMessageToTopic">发送</el-button>
              </el-form-item>
            </el-form>  
            <p>结果通知</p>
            <div>{{sendToTopicForm.result}}              
            </div>
          </el-col>
          <el-col :span="12" style="padding-left:10px">
            <p>向设备{{cur_row.DeviceName}} 发送消息</p>
            <el-form label-width="40px" >
              <el-form-item label="内容">
                <el-input v-model="sendToDeviceForm.message" placeholder="发送内容"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button  size="medium" type="success" @click="sendMessageToDevice">发送</el-button>
              </el-form-item>
            </el-form>  
            <p>结果通知</p>
            <div>{{sendToDeviceForm.result}}              
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getProductList,
  addProduct,
  addDeviceByProduct,
  getDeviceByProduct,
  deleteDevice,
  getDeviceDetail,
  sendToTopic,
  sendToDevice
} from "@/api/product";
import waves from "@/directive/waves/index.js"; // 水波纹指令
import { parseTime } from "@/utils";
import jsonEditor from "@/components/jsonEditor";

export default {
  name: "table_device",
  directives: {
    waves
  },
  components: { jsonEditor },
  data() {
    return {
      list: null,
      listQuery: {
        page_limit: 10,
        total: 0,
        page: 1,
        ProductKey: this.$route.query.ProductKey
      },
      deviceForm: {
        DeviceName: "",
        ProductKey: this.$route.query.ProductKey
      },
      DeviceDailog: {
        visible: false,
        dialogStatus: "",
        textMap: {
          update: "编辑",
          create: "创建"
        }
      },
      //删除设备
      cur_row: {
        DeviceName:""
      },
      delDeviceDialogVisible: false,

      //设备信息
      deviceInfoDialogVisible: false,
      activeNames: ["1", "2", "3"],
      deviceInfo: {},
      statusInfo: {},
      shadowInfo: "[]",
      //设备通信
      deviceMessageDialogVisible: false,
      sendToTopicForm: {
        topicList: [],
        deviceId: "",
        cur_topic: "",
        message: "",
        result: ""
      },
      sendToDeviceForm: {
        message: "",
        result: ""
      },
      //
      tableKey: 0
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
    json(value) {
      return JSON.parse(value);
    }
  },
  created() {
    this.getList(this.listQuery);
  },
  methods: {
    getList(params) {
      this.listLoading = true;
      getDeviceByProduct(params).then(r => {
        this.list = r.data.data;
        this.total = r.data.total;
        this.listLoading = false;
      });
    },
    sortChange(val) {
      if (val.order == "ascending") {
        this.listQuery.asc = val.prop;
        if (this.listQuery.desc == val.prop) {
          this.listQuery.desc = null;
        }
      } else {
        this.listQuery.desc = val.prop;
        if (this.listQuery.asc == val.prop) {
          this.listQuery.asc = null;
        }
      }
      this.getList(this.listQuery);
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList(this.listQuery);
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList(this.listQuery);
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList(this.listQuery);
    },
    timeFilter(time) {
      if (!time[0]) {
        this.listQuery.start = undefined;
        this.listQuery.end = undefined;
        return;
      }
      this.listQuery.start = parseInt(+time[0] / 1000);
      this.listQuery.end = parseInt((+time[1] + 3600 * 1000 * 24) / 1000);
    },
    handleView(row) {
      //查看设备信息
      getDeviceDetail(row.id).then(r => {
        this.deviceInfo = r.data.device;
        this.statusInfo = r.data.status;
        this.shadowInfo = JSON.parse(r.data.shadow);
        this.deviceInfoDialogVisible = true;
      });
    },
    //通信
    handleMessage(row) {
      this.cur_row = row;
      this.sendToTopicForm.topicList = [
        {
          value: "/" + row.ProductKey + "/" + row.DeviceName + "/update",
          lable: "发布：/" + row.ProductKey + "/" + row.DeviceName + "/update"
        },
        {
          value: "/" + row.ProductKey + "/" + row.DeviceName + "/update/error",
          lable:
            "发布：/" + row.ProductKey + "/" + row.DeviceName + "/update/error"
        },
        {
          value: "/" + row.ProductKey + "/" + row.DeviceName + "/get",
          lable: "订阅：/" + row.ProductKey + "/" + row.DeviceName + "/get"
        }
      ];
      this.deviceMessageDialogVisible = true;
    },
    sendMessageToTopic() {
      sendToTopic(this.cur_row.id, {
        TopicFullName: this.sendToTopicForm.cur_topic,
        MessageContent: this.sendToTopicForm.message
      }).then(r => {
        this.sendToTopicForm.result = r;
      },r=>{
        this.sendToTopicForm.result = r;
      });
    },
    sendMessageToDevice() {
      sendToDevice(this.cur_row.id, {
        DeviceName: this.cur_row.DeviceName,
        RequestBase64Byte: this.sendToDeviceForm.message
      }).then(r => {
        this.sendToDeviceForm.result = r;
      },r=>{
        this.sendToDeviceForm.result = r.response.data;
      });
    },
    handleCreate() {
      this.resetTemp();
      this.DeviceDailog.dialogStatus = "create";
      this.DeviceDailog.visible = true;
    },
    handleUpdate(row) {
      this.deviceForm = Object.assign({}, row);
      this.deviceForm.dialogStatus = "update";
      this.deviceForm.visible = true;
    },
    handleDelete(row) {
      this.delDeviceDialogVisible = true;
      this.cur_row = row;
    },
    create() {
      addDeviceByProduct(
        this.deviceForm.ProductKey,
        this.deviceForm.DeviceName
      ).then(r => {
        this.getList(this.listQuery);
        this.$notify({
          title: "成功",
          message: "创建成功",
          type: "success",
          duration: 2000
        });
        this.DeviceDailog.visible = false;
      });
    },
    update() {
      this.temp.timestamp = +this.temp.timestamp;
      for (const v of this.list) {
        if (v.id === this.temp.id) {
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.temp);
          break;
        }
      }
      this.dialogFormVisible = false;
      this.$notify({
        title: "成功",
        message: "更新成功",
        type: "success",
        duration: 2000
      });
    },
    delDevice() {
      deleteDevice(this.cur_row.id).then(r => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000
        });
        const index = this.list.indexOf(this.cur_row);
        this.list.splice(index, 1);
        this.cur_row = null;
        this.delDeviceDialogVisible = false;
      });
    },
    resetTemp() {
      this.deviceForm = {
        DeviceName: "",
        ProductKey: this.$route.query.ProductKey
      };
    },
    handleDownload() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../vendor/Export2Excel");
        const tHeader = ["序号", "设备名称", "设备id", "secret", "产品key", "时间"];
        const filterVal = [
          "id",
          "DeviceName",
          "DeviceId",
          "DeviceSecret",
          "ProductKey",
          "created_at"
        ];
        const data = this.formatJson(filterVal, this.list);
        export_json_to_excel(tHeader, data, "设备数据");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>

<style lang="scss" scoped>
.device-container {
  .el-dialog {
    max-height: 90%;
  }
  .device_message {
    width: 100%;
  }
}
</style>